#!/bin/bash
CWD=$(cd `dirname $0`;pwd)
cd "${CWD}"
source _env

STAMP="$(date +%s)"

[[ -f boot.yaml ]] && echo "find boot.yaml, skip configuring..." || {
  echo "generate boot.yaml ..."
  TMPFILE="boot.${STAMP}.yaml"
  if ${MINI_MODE}
  then
  cp -f boot-mini-tmp.yaml $TMPFILE
  else
  cp -f boot-tmp.yaml $TMPFILE
  fi
  sed -i "s|@OB_HOME_PATH@|${OB_HOME_PATH}|g" $TMPFILE
  sed -i "s|@OB_MYSQL_PORT@|${OB_MYSQL_PORT}|g" $TMPFILE
  sed -i "s|@OB_RPC_PORT@|${OB_RPC_PORT}|g" $TMPFILE
  sed -i "s|@OB_ROOT_PASSWORD@|${OB_ROOT_PASSWORD}|g" $TMPFILE
  [ "${OB_DATA_DIR}" ] && echo "    data_dir: ${OB_DATA_DIR}" >> $TMPFILE
  [ "${OB_REDO_DIR}" ] && echo "    redo_dir: ${OB_REDO_DIR}" >> $TMPFILE
  echo "create boot dirs and deploy ob cluster ..."
  mkdir -p $OB_HOME_PATH
  if ${MINI_MODE}
  then
  obd cluster deploy "${OB_CLUSTER_NAME}" -c $TMPFILE && obd cluster tenant create "${OB_CLUSTER_NAME}" -n ${OB_TENANT_NAME} && obd cluster start "${OB_CLUSTER_NAME}" && obclient -h127.1 -uroot@${OB_TENANT_NAME} -A -P${OB_MYSQL_PORT} < init_tenant_user.sql && mv -f $TMPFILE boot.yaml
  else
  obd cluster autodeploy "${OB_CLUSTER_NAME}" -c $TMPFILE && obd cluster tenant create "${OB_CLUSTER_NAME}" -n ${OB_TENANT_NAME} && obclient -h127.1 -uroot@${OB_TENANT_NAME} -A -P${OB_MYSQL_PORT} < init_tenant_user.sql && mv -f $TMPFILE boot.yaml
  fi
}

[[ -f boot.yaml ]] && {
  echo "start ob cluster ..."
  obd cluster start $OB_CLUSTER_NAME
} && echo "boot success!" && exec /sbin/init